import { useMemo, forwardRef } from 'react'
import classnames from 'classnames'
import IconFont from '@/components/IconFont'
import styles from './index.module.less'

const Item = forwardRef((props, _) => {
  const { id, dirId, name, type, onClick, isCollapse, isShow } = props
  const icon = useMemo(() => {
    const icons = {
      dir: 'icon-folder',
      dashboard: 'icon-dashboard',
      dataset: 'icon-sql'
    }
    return icons[type] || ''
  }, [type])

  const collapseIcon = useMemo(() => (isCollapse ? 'icon-pull-up' : 'icon-drop-down'), [isCollapse])

  // 文件夹下 item 样式
  const style = useMemo(
    () => (type !== 'dir' && dirId ? { marginLeft: '22px' } : {}),
    [type, dirId]
  )

  return (
    <>
      {isShow ? (
        <li key={id} className={styles.item} onClick={() => onClick(props)}>
          <div className="ellipsis">
            {type === 'dir' ? (
              <IconFont
                className={classnames(styles.icon, 'icon-color-base')}
                type={collapseIcon}
              />
            ) : null}
            <IconFont style={style} className={styles.icon} type={icon} />
            {name}
          </div>
        </li>
      ) : null}
    </>
  )
})

const DirTree = ({ data, onItem }) => {
  return (
    <div className={styles.dirtree}>
      <div className={styles.title}>仪表盘</div>
      <ul className={styles['tree-list']}>
        {data.map(item => <Item key={item.id} {...item} onClick={onItem} />)}
      </ul>
    </div>
  )
}

export default DirTree
